/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (root == NULL) {
            return;
        }
        TreeNode *cur = NULL;
        flattenHelper(root, cur);

    }

    void flattenHelper(TreeNode *root, TreeNode *&cur) {
        if (cur) {
            cur->right = root;
        }
        cur = root;
        TreeNode *right = root->right;
        TreeNode *left = root->left;

        root->right = root->left = NULL;
        if (left) {
            flattenHelper(left, cur);
        }
        if (right) {
            flattenHelper(right, cur);
        }
    }

};
